package initialize

import (
	"context"
	"fmt"
	"go_final/mxshop_srvs/goods_srv/global"
	"go_final/mxshop_srvs/goods_srv/model"
	"log"
	"os"

	"go.uber.org/zap"

	"github.com/olivere/elastic/v7"
)

func InitEs() {
	host := fmt.Sprintf("http://%s:%d", global.ServerConfig.ElasticInfo.Host, global.ServerConfig.ElasticInfo.Port)
	// 打印elasticsearch的执行语句
	logger := log.New(os.Stdout, "mxshop", log.LstdFlags)
	var err error
	global.EsClient, err = elastic.NewClient(
		elastic.SetURL(host),
		elastic.SetSniff(false),
		elastic.SetTraceLog(logger),
	)
	if err != nil {
		zap.S().Info("初始化elasticsearch失败", err.Error())
		panic(err)
	}

	// 新建mapping和index
	// 检查index存不存在
	exist, err := global.EsClient.IndexExists(model.EsGoods{}.GetIndexName()).Do(context.Background())
	if err != nil {
		zap.S().Info("查询index失败", err.Error())
		panic(err)
	}

	if !exist {
		// Create a new index.
		createIndex, err := global.EsClient.CreateIndex("mygoods").BodyString(model.EsGoods{}.GetMapping()).Do(context.Background())
		if err != nil {
			// Handle error
			zap.S().Info("创建mygoods index失败", err.Error())
			panic(err)
		}
		if !createIndex.Acknowledged {
			// Not acknowledged
			zap.S().Info("创建mygoods index Acknowledged 失败", err.Error())
			panic(err)
		}
	}
}
